
//  WPHomeTableViewController.m
//  wobingwoyi
//
//  Created by WGP on 16/7/21.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPHomeViewController.h"
#import "WPSearchVC.h"
#import "WPSearchView.h"
#import "WPHomeContentView.h"
#import "WPSecondView.h"
#import "WPThirdView.h"
#import "WPUpdateDataVC.h"
#import "WPTabBarController.h"
#import "WPCommunicationCommunityVC.h"
#import "WPDiseaseTypesVC.h"
#import "WPMoreDetailVC.h"
#import "WPMineLoginVC.h"
#import "WPLoopView.h"
#import "WPBanderPageVC.h"
#import "WPAlertView.h"
#import "WPHomeNavigationController.h"

#define  FIRST_CELL @"first"
#define  SECOND_CELL @"second"

@interface WPHomeViewController ()<WPSearchViewDelegate,WPSecondViewDelegate,WPThirdViewDelegate>

@property(nonatomic,strong)WPHomeContentView *contentView;
@property(nonatomic,strong)NSMutableArray *imagesArr;
@property(nonatomic,strong)NSMutableArray *linkUrlsArr;
@property(nonatomic,strong)NSMutableArray *pageTitlesArr;
@property(nonatomic,strong)WPLoopView *loopView;

@property(nonatomic,strong)UIImageView *imageView;

@end


@implementation WPHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    WPSearchView *searchView = [[WPSearchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-2*15, 30)];
    self.navigationItem.titleView = searchView;
    searchView.delegate = self;
    
    [self setupUI];
    
    __weak typeof(self) weakSelf = self;
    self.newVersionBlock = ^()
    {
        [weakSelf newVersion];
    };
}

-(void)guideImageViewDidClick:(UITapGestureRecognizer *)tgr
{
    [self.imageView removeFromSuperview];
}

-(void)newVersion
{
//        判断版本更新
        NSString *url = @"version/getVersion_iOS.do";
    
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
            if ([responseObject[@"result"] isEqualToString:@"success"])
            {
                NSString *versionStr = responseObject[@"detail"][@"versionNumber"];
    
                if ([self isNewVersion:versionStr])
                {
                    [self showNewVersionWindowWith:responseObject[@"detail"][@"updateMessage"]];
                }
            }
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull eror) {
            
        }];
}

#pragma mark - 是否新版本
-(BOOL)isNewVersion:(NSString *)version
{

    //    1.获得当前版本
    NSString *currentVersion = (NSString *)[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    
    //    3.对比
    if ([version compare:currentVersion options:NSNumericSearch] == NSOrderedDescending)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

-(void)showNewVersionWindowWith:(NSArray *)titles
{
    WPAlertView *alertView = [[WPAlertView alloc] initWithTitle:@"发现版本更新" delegate:nil contentTitle:titles];
    [alertView show];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    __weak typeof(self) weakSelf = self;
    self.firstUsing = ^{
    
        //第一次使用
        if(![[NSUserDefaults standardUserDefaults] boolForKey:isFirst_Home])
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirst_Home];
            
            //        判断是不是第一次使用
            NSString *imageName = nil;
            if (SCREEN_WIDTH < 375)
            {
                imageName = @"Home_first_using5";
            }
            else if(SCREEN_WIDTH < 414)
            {
                imageName = @"Home_first_using6";
            }
            else
            {
                imageName = @"Home_first_using6p";
            }
            
            UIImageView *guideImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
            weakSelf.imageView = guideImageView;
            guideImageView.userInteractionEnabled = YES;
            UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
            [keyWindow addSubview:guideImageView];
            
            [guideImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(keyWindow);
            }];
            
            UITapGestureRecognizer *TGR = [[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(guideImageViewDidClick:)];
            [guideImageView addGestureRecognizer:TGR];
        }
        
    };
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self setSCrollViewViewContentSize];
    
    self.firstUsing();
}


-(void)setupUI
{
    self.contentView = [[WPHomeContentView alloc] init];
    
    
    ReachabilityStatus status = [[RealReachability sharedInstance] currentReachabilityStatus];
    if (status == RealStatusNotReachable)
    {
//        刚开始没有网的的情况下
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChanged:) name:kRealReachabilityChangedNotification object:nil];
    }
    
    NSString *url = @"banner/findBanners.do";
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            NSArray *dicts = responseObject[@"detail"];
            for (NSDictionary *dict in dicts)
            {
                [self.imagesArr  addObject:dict[@"imageIos"]];
                [self.linkUrlsArr addObject:dict[@"linkUrl"]];
                [self.pageTitlesArr addObject:dict[@"title"]];
            }
            
            self.loopView.URLStrs = self.imagesArr;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    self.loopView = [[WPLoopView alloc] initWithURLStrs:self.imagesArr titles:nil didSelected:^(NSInteger index) {
        
        //        图片点击
        
        if(self.linkUrlsArr[index])
        {
                WPBanderPageVC *vc = [WPBanderPageVC new];
                vc.pageURL = self.linkUrlsArr[index];
                vc.pageTitle = self.pageTitlesArr[index];
                
                ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:vc];
                [self presentViewController:nav animated:YES completion:nil];
        }
        
    }];
    
    self.loopView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH/BANDER_SCALE);
    [self.contentView addSubview:self.loopView];

    
    self.contentView.secondView.delegate = self;
    self.contentView.thirdView.delegate = self;

    self.contentView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.contentView];
   
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}


- (void)networkChanged:(NSNotification *)notification
{
    RealReachability *reachability = (RealReachability *)notification.object;
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    if(status != RealStatusNotReachable)
    {
        NSString *url = @"banner/findBanners.do";
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if ([responseObject[@"result"] isEqualToString:@"success"])
            {
                NSArray *dicts = responseObject[@"detail"];
                
                //防止出现多个重复的bnner图,先清空之前的
                [self.imagesArr removeAllObjects];
                [self.linkUrlsArr removeAllObjects];
                [self.pageTitlesArr removeAllObjects];
                
                for (NSDictionary *dict in dicts)
                {
                    [self.imagesArr  addObject:dict[@"imageIos"]];
                    [self.linkUrlsArr addObject:dict[@"linkUrl"]];
                    [self.pageTitlesArr addObject:dict[@"title"]];
                    
                }
//                重新付给轮播器
                self.loopView.URLStrs = self.imagesArr;
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
//        移除通知
        [[NSNotificationCenter defaultCenter] removeObserver:self name:kRealReachabilityChangedNotification object:nil];
    }
}

-(void)setSCrollViewViewContentSize
{
    CGFloat contentHeight = 0;
    for (UIView *subView in self.contentView.subviews) {

        contentHeight += subView.bounds.size.height;
    }
    self.contentView.contentSize = CGSizeMake(0, contentHeight+7 + 15);
}



#pragma mark - searchBar的代理方法
-(void)WPSearchViewDelegate:(UIView *)searchBar
{
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:[WPSearchVC new] animated:NO];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark - secondView的代理方法
-(void)WPSecondViewOfFirstSubviewDelegate:(WPSecondView *)secondView
{
    
    if ([WPUserAccountViewModel sharedInstance].userLogin)
    {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WPUpdateDataVC" bundle:nil];
        UINavigationController *nvc = [sb instantiateInitialViewController];
        WPUpdateDataVC *vc = nvc.viewControllers[0];
        vc.isJump = YES;
        
        [self.navigationController presentViewController:nvc animated:YES completion:nil];
    }
    else
    {
        
        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{
        
                WPMineLoginVC *vc = [WPMineLoginVC new];
                [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
            vc.successLoginBlock = ^
            {
                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WPUpdateDataVC" bundle:nil];
                UINavigationController *nvc = [sb instantiateInitialViewController];
                WPUpdateDataVC *vc = nvc.viewControllers[0];
                vc.isJump = YES;
                
                [self.navigationController presentViewController:nvc animated:YES completion:nil];
            };
        }];
        
    }

}

-(void)WPSecondViewOfSecondSubviewDelegate:(WPSecondView *)secondView
{

    WPCommunicationCommunityVC *ccVC = [WPCommunicationCommunityVC new];
    ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)WPThirdViewDelegateWith:(WPThirdView *)thirdView diseaseType:(WPDiseaseTypes)diseaseType
{
    if (diseaseType == WPDiseaseTypesFirst)
    {
        WPDiseaseTypesVC *ccVC = [WPDiseaseTypesVC new];
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
        ccVC.diseaseTitle = @"category1";
        ccVC.isFiveDiseases = YES;
        [self presentViewController:nav animated:YES completion:nil];
    }
    else if(diseaseType == WPDiseaseTypesSecond)
    {
        WPDiseaseTypesVC *ccVC = [WPDiseaseTypesVC new];
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
        ccVC.diseaseTitle = @"category2";
        ccVC.isFiveDiseases = YES;
        [self presentViewController:nav animated:YES completion:nil];
    }
    else if (diseaseType == WPDiseaseTypesThird)
    {
        WPDiseaseTypesVC *ccVC = [WPDiseaseTypesVC new];
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
        ccVC.diseaseTitle = @"category3";
        ccVC.isFiveDiseases = YES;
        [self presentViewController:nav animated:YES completion:nil];
    }
    else if(diseaseType == WPDiseaseTypesFourth)
    {
        WPDiseaseTypesVC *ccVC = [WPDiseaseTypesVC new];
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
        ccVC.diseaseTitle = @"category4";
        ccVC.isFiveDiseases = YES;
        [self presentViewController:nav animated:YES completion:nil];
    }
    else if (diseaseType == WPDiseaseTypesFifth)
    {
        WPDiseaseTypesVC *ccVC = [WPDiseaseTypesVC new];
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
        ccVC.diseaseTitle = @"category5";
        ccVC.isFiveDiseases = YES;
        [self presentViewController:nav animated:YES completion:nil];
    }
    else if (diseaseType == WPDiseaseTypesSixth)
    {
        //更多疾病
        WPMoreDetailVC *ccVC = [WPMoreDetailVC new];
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:ccVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

-(NSMutableArray *)imagesArr
{
    if (_imagesArr == nil)
    {
        _imagesArr = [NSMutableArray array];
    }
    return _imagesArr;
}

-(NSMutableArray *)linkUrlsArr
{
    if (_linkUrlsArr == nil)
    {
        _linkUrlsArr = [NSMutableArray array];
    }
    return _linkUrlsArr;
}

-(NSMutableArray *)pageTitlesArr
{
    if (_pageTitlesArr == nil)
    {
        _pageTitlesArr = [NSMutableArray array];
    }
    return _pageTitlesArr;
}

@end
